import xml.dom.minidom
import xml.dom

def getText(nodelist):
    rc = []
    if isinstance(nodelist,xml.dom.Node):
        rc.append(nodelist.firstChild.data)
    else:    
        for node in nodelist:
            if node.firstChild == None:
                rc.append('None')
            elif node.firstChild.nodeType == node.TEXT_NODE:
                rc.append(node.firstChild.data)
    return ''.join(rc)

def handleXML(xml):
    res = ""
    tables = xml.getElementsByTagName("table")
    res += handleTables(tables)
    return res

def handleTables(tables):
    res = ""    
    for each_tbl in tables:
        res += '<div class="accordion">' + handleTable(each_tbl) + '</div>'
        res += "<br><br>"
    return res
        
def handleTable(table):
    res = ""
    res += handleTableName(table.getElementsByTagName("name")[0])
    res += handleTableDescription(table.getElementsByTagName("description")[0])
    res += handleTableColumns(table.getElementsByTagName("column"))
    return res
    
def handleTableName(name):
    return '<p class="heading">%s <img style="float:right" src="/static/arrow.png"/> </p>' % getText(name)

def handleTableDescription(desc):
    return '<div id="desc">Description: %s </div>' % getText(desc)


def handleTableColumns(columns):
    res='<div class="content">'
    res += '<p style="background-color:#4E4848;color:white;padding-left:10px;padding-top:5px;margin-bottom:10px;border:1px solid gray;height:20px;">Table Columns:<br><br></p>'
    for column in columns:
        res += '<p class="column_heading">' + handleColumnName(column.getElementsByTagName("name")) + '</p>'
        res += '<ul class="column_content">'
        res += handleColumn(column)
        res += "</ul>"
        res += "<br>"
    res += "</div>"    
    return res    

def handleColumn(column):
    res = ""
    res += handleColumnDescription(column.getElementsByTagName("description"))
    res += handleColumnUnit(column.getElementsByTagName("unit"))
    res += handleColumnUCD(column.getElementsByTagName("ucd"))
    return res
    
def handleColumnName(name):
    return '<a class="expand">%s</a> <img style="float:right" src="/static/arrow.png"/>' % getText(name)

def handleColumnDescription(desc):
    return "<li>Description: %s</li>" % getText(desc)

def handleColumnUnit(unit):
    return "<li>Unit: %s</li>" % getText(unit)

def handleColumnUCD(ucd):        
    return "<li>UCD: %s</li>" % getText(ucd)

